import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getAccessToken, removeAccessToken, setAccessToken } from '@/utils/accessToken'
import { useSnackbar } from '@/composables/useSnackbar'
import { getStorage, setStorage, removeStorage } from '@/utils/storage'
import { getListAll } from '@/api/system/user/userManagement'

// 用户信息接口
export interface UserInfo {
  id: string
  realName: string
  email: string
  avatar?: string
  department?: string
  position?: string
  mobile?: string
  status?: string
  [key: string]: any
}

export const useUserStore = defineStore('user', () => {
  const token = ref(getAccessToken())
  const username = ref('')
  const avatar = ref('')
  const permissions = ref<string[]>([])
  const perms = ref<string[]>([])

  // 添加所有用户列表管理 - 从缓存初始化
  const allUsers = ref<UserInfo[]>(getStorage('allUsers') || [])
  const usersLoading = ref(false)
  const usersLastUpdated = ref<Date | null>(getStorage('usersLastUpdated') ? new Date(getStorage('usersLastUpdated')) : null)

  const { showSnackbar } = useSnackbar()

  function setToken(accessToken: string) {
    token.value = accessToken
    setAccessToken(accessToken)
  }

  function setUsername(name: string) {
    username.value = name
  }

  function setAvatar(img: string) {
    avatar.value = img
  }

  function setPermissions(roles: string[]) {
    permissions.value = roles
  }

  function setPerms(permissionList: string[]) {
    perms.value = permissionList
  }

  // 设置所有用户列表
  function setAllUsers(users: UserInfo[]) {
    allUsers.value = users
    usersLastUpdated.value = new Date()
    // 缓存到本地存储
    setStorage('allUsers', users)
    setStorage('usersLastUpdated', usersLastUpdated.value.toISOString())
  }

  // 加载所有用户（登录时调用）
  async function loadAllUsers(forceRefresh = false) {
    // 如果正在加载，直接返回
    if (usersLoading.value) return

    // 如果不是强制刷新且有缓存数据，检查是否需要更新
    if (!forceRefresh && allUsers.value.length > 0 && !shouldRefreshUsers()) {
      console.log('用户数据从缓存加载:', allUsers.value.length, '个用户')
      return
    }

    // usersLoading.value = true
    // try {
    //   // 这里应该调用实际的API获取用户数据
    //   const { data } = await getListAll()

    //   // 暂时使用模拟数据
    //   const mockUsers: UserInfo[] = data

    //   setAllUsers(mockUsers)
    //   console.log('用户列表API加载成功:', mockUsers.length, '个用户')
    // } catch (error) {
    //   console.error('加载用户列表失败:', error)
    //   showSnackbar({ text: '加载用户列表失败', color: 'error' })
    // } finally {
    //   usersLoading.value = false
    // }
  }

  // 检查是否需要刷新用户列表（可选）
  function shouldRefreshUsers(): boolean {
    if (!usersLastUpdated.value) return true
    const hoursSinceUpdate = (Date.now() - usersLastUpdated.value.getTime()) / (1000 * 60 * 60)
    return hoursSinceUpdate > 1 // 1小时后需要刷新
  }

  // 根据ID获取用户信息
  async function getUserById(id: string): Promise<UserInfo | undefined> {
    let user = allUsers.value.find(user => user.id === id)

    // 如果用户不存在且缓存不为空，尝试刷新缓存
    if (!user && allUsers.value.length > 0) {
      console.log(`用户ID ${id} 不存在，尝试刷新缓存...`)
      await loadAllUsers(true) // 强制刷新
      user = allUsers.value.find(user => user.id === id)

      if (user) {
        console.log(`刷新缓存后找到用户: ${user.realName}`)
      } else {
        console.log(`刷新缓存后仍未找到用户ID: ${id}`)
      }
    }

    return user
  }

  // 根据ID获取用户名
  async function getUserNameById(id: string): Promise<string> {
    const user = await getUserById(id)
    return user?.realName || id || '未知用户'
  }

  // 同步版本的方法（不会触发刷新，用于UI显示）
  function getUserByIdSync(id: string): UserInfo | undefined {
    return allUsers.value.find(user => user.id === id)
  }

  function getUserNameByIdSync(id: string): string | null {
    const user = getUserByIdSync(id)
    return user?.realName || id || null
  }

  // 根据部门筛选用户
  function getUsersByDepartment(department: string): UserInfo[] {
    return allUsers.value.filter(user => user.department === department)
  }

  // 根据状态筛选用户
  function getUsersByStatus(status: 'active' | 'inactive' | 'all'): UserInfo[] {
    if (status === 'all') return allUsers.value
    return allUsers.value.filter(user => user.status === status)
  }

  function resetToken() {
    permissions.value = []
    perms.value = []
    token.value = ''
    // 清除用户列表缓存
    allUsers.value = []
    usersLastUpdated.value = null
    removeAccessToken()
    removeStorage('allUsers')
    removeStorage('usersLastUpdated')
  }

  return {
    token,
    username,
    avatar,
    permissions,
    perms,
    // 用户列表相关
    allUsers,
    usersLoading,
    usersLastUpdated,
    setToken,
    setUsername,
    setAvatar,
    setPermissions,
    setPerms,
    // 用户列表管理方法
    setAllUsers,
    loadAllUsers,
    shouldRefreshUsers,
    getUserById,
    getUserNameById,
    getUserByIdSync,
    getUserNameByIdSync,
    getUsersByDepartment,
    getUsersByStatus,
    resetToken
  }
}) 